package com.marketingexpert.service.marketingmgnt.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.impl.StdScheduler;
import org.springframework.dao.DataAccessException;
import org.springframework.util.Assert;

import com.marketingexpert.config.Placeholder;
import com.marketingexpert.config.SystemErrorCode;
import com.marketingexpert.dao.AutoRecommentDao;
import com.marketingexpert.dao.MarketingDao;
import com.marketingexpert.domain.AutoRecomment;
import com.marketingexpert.domain.Discount;
import com.marketingexpert.domain.DiscountNumPrice;
import com.marketingexpert.domain.DiscountUserMessage;
import com.marketingexpert.domain.Trend;
import com.marketingexpert.domain.User;
import com.marketingexpert.domain.UserFuncEnable;
import com.marketingexpert.domain.UserType;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.messagemgnt.impl.MessageServiceImpl;
import com.marketingexpert.service.snsmgnt.SnsService;
import com.marketingexpert.service.snsmgnt.SnsServiceFactory;
import com.marketingexpert.service.storemgnt.AbstractActivity;
import com.marketingexpert.service.storemgnt.MarketingItem;
import com.marketingexpert.service.storemgnt.MarketingPromotion;
import com.marketingexpert.service.storemgnt.StoreService;
import com.marketingexpert.service.storemgnt.StoreServiceFactory;
import com.marketingexpert.service.storemgnt.taobao.domain.impl.TaobaoItem;
import com.marketingexpert.service.usermgnt.UserService;
import com.marketingexpert.util.ContextHolder;
import com.marketingexpert.util.FillPlaceholder;
import com.marketingexpert.util.Resources;
import com.marketingexpert.util.WebUtils;
import com.taobao.api.domain.Activity;
import com.taobao.api.domain.Coupon;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Meal;

public class MarketingServiceImpl extends MarketingServiceBaseImpl {

	private static Logger logger = Logger.getLogger(MarketingServiceImpl.class);

	private UserService userService;

	private MarketingDao marketingDao;
	private AutoRecommentDao autoRecommentDao;

	private SnsServiceFactory snsServiceFactory;

	private SystemErrorCode systemErrorCode;

	private StoreServiceFactory storeServiceFactory;

	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	public void publishRetweetMarketing(Map<String, Object> params)
			throws MarketingExpertException {

		// TODO1:�����ʼʱ����Ϊһ������,�������Ϣ���͵�΢��(Ҫ���ܴ���΢����id,������),������discount����
		// TODO2:�����ʱ����Ϊһ������,���ں���΢��ת�����,��Ӧ�ĸ�����Ʒ�۸�
		try {
		String group = this.setActivityStart(params);
		this.setActivityEnd(params, group);
		} catch(MarketingExpertException e) {
			throw e;
		}

	}

	/*
	 * ����û��趨�Ļ����ʱ��,���һ����ʱ����,���񴥷�ʱ,����ݿ���ȡ����Ӧ��discount����,��ȡ�����ʼʱ������΢��
	 * ��Ϣ��id,��ѯ��ת�����,������Ʒ�۸�
	 */
	private void setActivityEnd(Map<String, Object> params, String group) {
		Map<String, String> time = (Map<String, String>) params.get("time");

		Discount saveDiscountObj = (Discount) params.get("saveDiscountObj");
		String endDate = (String) time.get("endDate");
		String endHour = (String) time.get("endHour");
		String endMinite = (String) time.get("endMinite");

		int separatorOne = endDate.indexOf("/"); //$NON-NLS-1$
		int separatorTwo = endDate.lastIndexOf("/"); //$NON-NLS-1$

		String year = endDate.substring(0, separatorOne);
		String month = endDate.substring(separatorOne + 1, separatorTwo);
		String day = endDate.substring(separatorTwo + 1, endDate.length());

		String cronExpression = "0 " + endMinite + " " + endHour + " " + day + " " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
				+ month + " ? " + year; //$NON-NLS-1$

		try {

			StdScheduler sched = (StdScheduler) ContextHolder
					.getBean("schedulerFactoryBean");

			CronExpression cron = new CronExpression(cronExpression);

			sched.start();

			// ���һ�������,Ϊjobdetail����
			String randomIdentify = String.valueOf(WebUtils.getRondom());

			JobDetail jobDetail = new JobDetail("marketingEndMessage_"
					+ randomIdentify, "marketingEndMessage",
					MarketingEndJob.class);
			CronTrigger trigger = new CronTrigger("marketingEndTrigger_"
					+ randomIdentify, "triggerEndGroup");

			trigger.setCronExpression(cron);

			jobDetail.getJobDataMap().put("parentUserId",
					saveDiscountObj.getUserId());
			jobDetail.getJobDataMap().put("group", group);

			sched.scheduleJob(jobDetail, trigger);
		} catch (SchedulerException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException("07", Resources.getString("MarketingServiceImpl.InvalidDate"));
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException("07", Resources.getString("MarketingServiceImpl.InvalidDate"));
		}
	}

	/*
	 * ������������,����û��趨�Ļ��ʼʱ��
	 */
	private String setActivityStart(Map<String, Object> params) {

		Map<String, String> time = (Map<String, String>) params.get("time");
		// Ҫ�����discount����(��Ҫ������Ӫ����Ϣ���ͺ��ȡ��΢����Ϣid�������ݿ�)
		Discount saveDiscountObj = (Discount) params.get("saveDiscountObj");
		
		String imageSavePath = saveDiscountObj.getItemPicUrl();
		String weiboContent = (String) params.get("recommend");
		String itemUrl = (String) params.get("itemUrl");
		String activityName = (String) params.get("activityName");
		String itemName = (String) params.get("itemName");
		String sendtopublic = (String) params.get("sendtopublic");
		String activityType = (String) params.get("activityType");
		int pid = (Integer)params.get("pid");
		String[] userIds = (String[]) params.get("weiboUserIds");

		String postDate = (String) time.get("startDate");
		String hour = (String) time.get("startHour");
		String minite = (String) time.get("startMinite");

		String cronExpression = null;
		if (postDate != null && !postDate.trim().equals("")) { //$NON-NLS-1$
			int separatorOne = postDate.indexOf("/"); //$NON-NLS-1$
			int separatorTwo = postDate.lastIndexOf("/"); //$NON-NLS-1$

			String year = postDate.substring(0, separatorOne);
			String month = postDate.substring(separatorOne + 1, separatorTwo);
			String day = postDate
					.substring(separatorTwo + 1, postDate.length());

			cronExpression = "0 " + minite + " " + hour + " " + day + " " 
					+ month + " ? " + year;

		}

		// ���ڶ�ʱ��Ϣ,���಻��Ҫ����task
		try {

			StdScheduler sched = (StdScheduler) ContextHolder.getBean("schedulerFactoryBean");

			CronExpression cron = new CronExpression(cronExpression);
			sched.start();
			// ���һ�������,Ϊjobdetail����
			String randomIdentify = String.valueOf(String.valueOf(WebUtils
					.getRondom()));
			JobDetail jobDetail = new JobDetail("marketingMessage_"
					+ randomIdentify, "marketingMessageJobDetailGroup",
					MarketingStartJob.class);
			CronTrigger trigger = new CronTrigger("marketingTrigger_"
					+ randomIdentify, "marketingMessageTriggerGroup");
			trigger.setCronExpression(cron);

			jobDetail.getJobDataMap().put("weiboContent", weiboContent);
			jobDetail.getJobDataMap().put("imageSavePath", imageSavePath);
			jobDetail.getJobDataMap().put("activityName", activityName);
			jobDetail.getJobDataMap().put("userIds", userIds);
			jobDetail.getJobDataMap().put("itemName", itemName);
			jobDetail.getJobDataMap().put("saveDiscountObj", saveDiscountObj);
			jobDetail.getJobDataMap().put("group", randomIdentify);
			jobDetail.getJobDataMap().put("sendtopublic", sendtopublic);
			jobDetail.getJobDataMap().put("activityType", activityType);
			jobDetail.getJobDataMap().put("itemUrl", itemUrl);
			jobDetail.getJobDataMap().put("pid", pid);

			sched.scheduleJob(jobDetail, trigger);
			return randomIdentify;
		} catch (SchedulerException e) {
			logger.warn(Resources.getString("MarketingServiceImpl.startScdulerFailed"), e);
			throw new MarketingExpertException("07", Resources.getString("MarketingServiceImpl.InvalidDate"));
		} catch (ParseException e) {
			logger.warn(Resources.getString("MarketingServiceImpl.InvalidDate"), e); //$NON-NLS-1$
			throw new MarketingExpertException("07", Resources.getString("MarketingServiceImpl.InvalidDate"));
		}
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public MarketingDao getMarketingDao() {
		return marketingDao;
	}

	public void setMarketingDao(MarketingDao marketingDao) {
		this.marketingDao = marketingDao;
	}

	public SnsServiceFactory getSnsServiceFactory() {
		return snsServiceFactory;
	}

	public void setSnsServiceFactory(SnsServiceFactory snsServiceFactory) {
		this.snsServiceFactory = snsServiceFactory;
	}

	/*
	 * ����һ���Զ��Ƽ�����(non-Javadoc)
	 * 
	 */
	public int saveAutoRecomment(AutoRecomment ar)
			throws MarketingExpertException {

		try {
			return getAutoRecommentDao().saveAutoRecomment(ar);
		} catch (DataAccessException e) {
			throw new MarketingExpertException(e);
		}
	}

	public AutoRecommentDao getAutoRecommentDao() {
		return autoRecommentDao;
	}

	public void setAutoRecommentDao(AutoRecommentDao autoRecommentDao) {
		this.autoRecommentDao = autoRecommentDao;
	}

	/*
	 * ���Id��ѯһ���Զ��Ƽ�����������
	 * 
	 * @seecom.marketingexpert.service.marketingmgnt.MarketingService#
	 * queryAutoRecommentById(int)
	 */
	public AutoRecomment queryAutoRecommentById(int autoRecId)
			throws MarketingExpertException {

		try {
			return getAutoRecommentDao().queryAutoRecommentById(autoRecId);
		} catch (DataAccessException e) {
			throw new MarketingExpertException(e);
		}

	}
	/*
	 * �Ƽ���Ʒ
	 */
	public boolean sendItemRecomment(String content, User weiboUser, Item item,
			Placeholder placeHolder) {
		try {
			String sendContent = FillPlaceholder.generateItemRecContent(
					content, placeHolder, item, getSnsServiceFactory());

			SnsService weiboService = WebUtils.getSnsService(weiboUser,
					getSnsServiceFactory());
			String messageId = weiboService.update(weiboUser.getAccessToken(), weiboUser
					.getSecret(), sendContent);
			
			if (messageId == null) {
				return false;
			}			
			if(placeHolder.getSendToPublic() != null && placeHolder.getSendToPublic().equals("true")) {
				StringBuilder sb = new StringBuilder();
				sb.append(placeHolder.getTrendIdentity()).append(Resources.getString(placeHolder.getActivityType())).
								append("|").append(placeHolder.getLimitDiscount()).append(placeHolder.getTrendIdentity());
				
				User publicUser = getUserService().queryUserByUId(placeHolder.getPublicWeiboId());
				try {					
					weiboService.repostWeibo(messageId, sb.toString(), 0, publicUser.getAccessToken(), publicUser.getSecret());
				} catch(MarketingExpertException e) {
					logger.error(e.getErrMsg(), e);
				} catch(Exception e) {
					logger.error(e.getMessage(), e);
				}
			}				
			return true;
		} catch (MarketingExpertException e) {
			throw e;
		} catch(Exception e) {
			throw new MarketingExpertException("10","����Ƶ�ʹ��,����Բ�ȡ���������Ƽ��ķ�ʽ");
		}

	}

	/*
	 * ���һ����Ϣ
	 */
	public String generateContent(String content, AbstractActivity activity,
			Placeholder placeholder) {

		return FillPlaceholder.generatateContent(content, activity,
				placeholder, getSnsServiceFactory());
	}

	/*
	 * ��ѯ�û����е��Զ��Ƽ�ģ��
	 * 
	 * @seecom.marketingexpert.service.marketingmgnt.MarketingService#
	 * queryAutoRecommentByUserId(java.lang.String)
	 */
	public AutoRecomment queryAutoRecommentByUserId(int parentUserId)
			throws MarketingExpertException {
		try {
			return getAutoRecommentDao().queryAutoRecommentByUserId(
					parentUserId);
		} catch (DataAccessException e) {
			throw new MarketingExpertException(e);
		}

	}

	/*
	 * �����û����е��Զ��Ƽ�ģ��
	 * 
	 * @seecom.marketingexpert.service.marketingmgnt.MarketingService#
	 * updateAutoRecomment(com.marketingexpert.domain.AutoRecomment)
	 */
	public int updateAutoRecomment(AutoRecomment ar) {
		try {
			return getAutoRecommentDao().updateAutoRecomment(ar);
		} catch (DataAccessException e) {
			throw new MarketingExpertException(e);
		}
	}

	public StoreServiceFactory getStoreServiceFactory() {
		return storeServiceFactory;
	}

	public void setStoreServiceFactory(StoreServiceFactory storeServiceFactory) {
		this.storeServiceFactory = storeServiceFactory;
	}

	/*
	 * ��ѯ�����
	 * 
	 * @param activityId
	 * 
	 * @param sessionKey
	 * 
	 * @return ��Լ���һ�����Żݾ�
	 */
	public Map<String, Object> querySingleActivity(String activityId,
			String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			List<Activity> activity = taobaoService.getActivity(activityId,
					sessionKey);
			List<Coupon> coupon = taobaoService.getExistCoupon(sessionKey, 0L,
					activity.get(0).getCouponId());

			Map<String, Object> results = new HashMap<String, Object>();
			results.put("activity", activity.get(0));
			results.put("coupon", coupon.get(0));
			return results;
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage() + ";" + e.getErrCode()
					+ ".MarketingServiceImpl Line 490", e);
			throw e;
		}
	}

	/**
	 * ��ѯ���е��Żݾ�(���Ը��Id��ѯ)
	 */
	public List<Coupon> getExistCoupon(String couponId, long pageNo,
			String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			List<Coupon> coupon = taobaoService.getExistCoupon(sessionKey, 0L,
					Long.parseLong(couponId));
			return coupon;
		} catch (MarketingExpertException e) {
			throw e;
		}

	}

	public List<AbstractActivity> batchQueryActivity(String activityId,
			String sessionKey) throws MarketingExpertException {

		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {

			List<AbstractActivity> activitys = taobaoService
					.getCouponActivity(activityId, sessionKey);

			return activitys;

		} catch (MarketingExpertException e) {
			logger.error(e.getMessage() + ";" + e.getErrCode()
					+ ".MarketingServiceImpl Line 490", e);
			throw e;
		}
	}

	/**
	 * ������ȡһ�鱦�����Ż�
	 * 
	 * @param itemIds
	 * @param sessionKey
	 * @return
	 */
	public List<MarketingPromotion> batchGetItemPromotion(String[] itemIds,
			String sessionKey, long pageNo) {
		try {
			List<MarketingPromotion> promotions = new ArrayList<MarketingPromotion>();
			for (String itemId : itemIds) {
				MarketingPromotion mps = this.getItemPromotion(itemId,sessionKey,pageNo);
				if (mps == null) {
					continue;
				}
					promotions.add(mps);
			}
			if (promotions.size() == 0) {
				return null;
			}
			return promotions;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	/**
	 * ��ȡ�����������Ż�
	 * 
	 * @param itemId
	 * @param sessionKey
	 * @param pageNo 
	 * @return
	 */
	public MarketingPromotion getItemPromotion(String itemId, String sessionKey, long pageNo) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			MarketingPromotion mp = taobaoService.getItemPromotion(itemId,sessionKey, pageNo);

			if (mp == null) {
				return null;
			}

			return mp;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	/*
	 * �Ƽ�һ����Ʒ���Ż���Ϣ
	 * 
	 * @seecom.marketingexpert.service.marketingmgnt.MarketingService#
	 * recommentItemPromotion(java.lang.String, com.marketingexpert.domain.User,
	 * com.marketingexpert.service.storemgnt.MarketingPromotion)
	 */
	public boolean recommentItemPromotion(String content, User weiboUser,
			MarketingPromotion mp, Placeholder placeholder) {

		try {
			String sendContent = FillPlaceholder.generatePromotionRecContent(
					content, mp, placeholder, getSnsServiceFactory());

			SnsService weiboService = WebUtils.getSnsService(weiboUser,
					getSnsServiceFactory());

			// ������ͼ
			String  messageId = weiboService.update(weiboUser.getAccessToken(), weiboUser.getSecret(), sendContent);

			if (messageId == null) {
				return false;
			}
			
			if(placeholder.getSendToPublic() != null && placeholder.getSendToPublic().equals("true")) {
				User publicUser = getUserService().queryUserByUId(placeholder.getPublicWeiboId());
				StringBuilder sb = new StringBuilder();
				sb.append(placeholder.getTrendIdentity()).append(Resources.getString(placeholder.getActivityType()))
				.append("|").append(placeholder.getLimitDiscount()).append(placeholder.getTrendIdentity());
				try {
					weiboService.repostWeibo(messageId, sb.toString(), 0, publicUser.getAccessToken(), publicUser.getSecret());
				} catch(MarketingExpertException e) {
					logger.error(e.getErrMsg(), e);
				}catch(Exception e) {
					logger.error(e.getMessage(), e);
				}
			}	
			return true;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	/**
	 * ��ѯ���������ײ�
	 */
	public List<Meal> queryMeals(long mealId, String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			return taobaoService.queryMeals(mealId, sessionKey);
		} catch (MarketingExpertException e) {
			throw e;
		}

	}

	/**
	 * ������ѯ���������ײ�
	 */
	public List<Meal> batchQueryMeals(long[] mealIdLong, String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			List<Meal> meals = new ArrayList<Meal>();

			for (long id : mealIdLong) {
				meals.add(taobaoService.queryMeals(id, sessionKey).get(0));
			}

			return meals;
		} catch (MarketingExpertException e) {
			throw e;
		}

	}

	/*
	 * �Ƽ��ײ�
	 * 
	 * @see
	 * com.marketingexpert.service.marketingmgnt.MarketingService#recommentMeal
	 * (com.taobao.api.domain.Meal, com.marketingexpert.domain.User,
	 * com.marketingexpert.config.Placeholder, java.lang.String)
	 */
	public boolean recommentMeal(Meal meal, User weiboUser,
			Placeholder placeholder, String content, MarketingItem item) {
		try {
			String sendContent = FillPlaceholder.generateMealRecContent(
					content, meal, placeholder, getSnsServiceFactory(), item
							.getDetailUrl());
			SnsService weiboService = WebUtils.getSnsService(weiboUser,
					getSnsServiceFactory());

			String messageId = weiboService.update(weiboUser.getAccessToken(),
					weiboUser.getSecret(), sendContent);
			if (messageId == null) {
				return false;
			} 
			
			if(placeholder.getSendToPublic() != null && placeholder.getSendToPublic().equals("true")) {
			
				StringBuilder sb = new StringBuilder();
				sb.append(placeholder.getTrendIdentity()).append(Resources.getString(placeholder.getActivityType()))
								.append("|").append(placeholder.getLimitDiscount()).append(placeholder.getTrendIdentity());
				
				User publicUser = getUserService().queryUserByUId(placeholder.getPublicWeiboId());
				try {
					weiboService.repostWeibo(messageId, sb.toString(), 0, publicUser.getAccessToken(), publicUser.getSecret());
				} catch(MarketingExpertException e) {
					logger.error(e.getErrMsg(), e);
				}catch(Exception e) {
					logger.error(e.getMessage(), e);
				}

			}
			
			return true;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	/*
	 * ��ȡһ������
	 * 
	 * @see
	 * com.marketingexpert.service.marketingmgnt.MarketingService#getSingleItem
	 * (long, java.lang.String)
	 */
	public MarketingItem getSingleItem(long itemId, String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			Item item = taobaoService.getSingleItem(itemId, sessionKey);
			MarketingItem mItem = new TaobaoItem(item);
			return mItem;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	public SystemErrorCode getSystemErrorCode() {
		return systemErrorCode;
	}

	public void setSystemErrorCode(SystemErrorCode systemErrorCode) {
		this.systemErrorCode = systemErrorCode;
	}

	/*
	 * �����Զ�Ӫ�����û�����Ļ���
	 * 
	 * @seecom.marketingexpert.service.marketingmgnt.MarketingService#
	 * saveAutoMarketingTrends(java.lang.String[], java.lang.String[],
	 * java.lang.String)
	 */
	public void saveAutoMarketingTrends(String[] trends, String[] weiboUserIds,
			String parentUserID) {
		try {
			User parentUser = getUserService().queryUserByUId(parentUserID);
			getMarketingDao().saveAutoMarketingTrends(trends, weiboUserIds,
					parentUser);
		} catch (DataAccessException e) {
			logger.error(Resources
					.getString("SaveTrendController.saveAutoMarketingFailed"),
					e);
			throw new MarketingExpertException(e);
		}

	}

	public List<Trend> queryAllTrendByUserId(int[] userIds, int index)
			throws MarketingExpertException {

		try {
			return getMarketingDao().queryAllTrendByUserId(userIds, index);
		} catch (DataAccessException e) {
			throw new MarketingExpertException(e);
		}
	}

	/**
	 * 从新浪微博查询自动营销的微博素材
	 * @param uid 用于查找的微博用户的id列表
	 * @return
	 * @throws MarketingExpertException
	 */
	public Map<String, Object> getOneTrendMessage(String uids)
			throws MarketingExpertException {
		SnsService snsService = getSnsServiceFactory().getService(SnsServiceFactory.SINA);
		return snsService.getOneTrendMessage(uids);
	}

	public String autoMarketingExecute(Map<String,Object> material,User user) throws MarketingExpertException {
		try {			
			SnsService snsService = WebUtils.getSnsService(user,getSnsServiceFactory());
			String content = (String)material.get("text");
			if(material.containsKey("picture") && material.get("picture") != null) {
				String messageId = snsService.upload(user.getAccessToken(), user.getSecret(), content, (File)material.get("picture"));
				
				return messageId;
			} else {
				return snsService.update(user.getAccessToken(), user.getSecret(),content);
			}
		} catch (MarketingExpertException e) {
			throw new MarketingExpertException(e);
		}
	}

	/**
	 * 
	 */
	public List<com.marketingexpert.service.snsmgnt.User> getNewFans(User user) {
		int cursor = 0;
		if (user.getUserType().equals(UserType.SINAWEIBO)) {
			cursor = -1;
		}
		List<com.marketingexpert.service.snsmgnt.User> fans = new ArrayList<com.marketingexpert.service.snsmgnt.User>();
		try {
			SnsService snsService = WebUtils.getSnsService(user,
					getSnsServiceFactory());
			List<com.marketingexpert.service.snsmgnt.User> queryedFans = snsService
					.getFollowedMeStatues(user.getAccessToken(), user
							.getSecret(), user.getUserId(), cursor);
			for (com.marketingexpert.service.snsmgnt.User fan : queryedFans) {
				if (!snsService.existsFriendship(user.getAccessToken(), user
						.getSecret(), user.getUserId(), fan.getId())) {
					fans.add(fan);
				}
			}
			return fans;
		} catch (MarketingExpertException e) {
			logger.error(e);
			throw e;
		}
	}

	/*
	 * ��ȡ����΢����ת����
	 * 
	 * @seecom.marketingexpert.service.statreport.StatReportService#
	 * getSingleWeiboRtCounts(java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	public int getSingleWeiboRtCounts(User user, String messageId)
			throws MarketingExpertException {

		try {
			SnsService snsService = WebUtils.getSnsService(user,
					getSnsServiceFactory());

			Assert.notNull(snsService);

			JSONArray rtCountsJson = snsService.getRtCtCounts(user
					.getAccessToken(), user.getSecret(), messageId);

			int rtCount = -1;
			if (user.getUserType().equals(UserType.SINAWEIBO)) {
				rtCount = rtCountsJson.getJSONObject(0).getInt("rt");
			} else {
				rtCount = rtCountsJson.getJSONObject(0).getInt("count");
			}
			return rtCount;
		} catch (MarketingExpertException e) {
			throw e;
		}
	}

	/*
	 * ͳ��΢��ת�����,�޸���Ʒ�۸�
	 * 
	 * @see
	 * com.marketingexpert.service.statreport.StatReportService#analysisWeiboRt
	 * (java.util.List, java.util.List)
	 */
	public void analysisWeiboRt(Discount discount)
			throws MarketingExpertException {

		StoreService storeService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);

		// �Ա��û�id,Ϊ�˻�ȡsessionKey
		String parentUserId = discount.getUserId();

		Assert.notNull(discount);

		// �ۿ�����,�����ת��������? ת�����ټ�����
		String discountType = discount.getDiscountType();

		// discount�����е��Żݲ���,��ת�������˼�����,��תһ�μ�����
		List<DiscountNumPrice> dnps = discount.getDnps();

		// discoutn���������з��͵�΢����ת�����Լ���Ӧ��΢���ʺ�
		List<DiscountUserMessage> dums = discount.getDums();

		// ͳ������,�����ͳ��
		String statType = discount.getStatType();

		// 1:�����ת��������
		int Rtcount = 0;// ʵ��ת����ͳ�ƽ��
		if (statType.equals("statsMaxRetweet")) {// �Ե���΢�����ת����Ϊ׼
			for (DiscountUserMessage dum : dums) {
				if (Rtcount < dum.getRetweetCounts()) {
					Rtcount = dum.getRetweetCounts();
				}
			}
		} else { // �Զ���΢����ת�����Ϊ׼
			for (DiscountUserMessage dum : dums) {
				Rtcount += dum.getRetweetCounts();
			}
		}

		// 2�������Ҫ����Ǯ��

		double minusRMB = 0; // Ҫ����Ǯ��
		if (discountType.equals("step")) {
			Collections.sort(dnps);

			if (Rtcount < Integer.parseInt(dnps.get(0).getRetweetNum())) { // û�ﵽ���������ת������
				minusRMB = 0;
			} else {

				for (int i = dnps.size() - 1; i > -1; i--) {
					DiscountNumPrice dnp = dnps.get(i);
					if (Integer.parseInt(dnp.getRetweetNum()) <= Rtcount) {
						minusRMB = Double.parseDouble(dnp.getDiscountRMB());
						break;
					}
				}
			}

		} else { // ת�����ټ�����
			minusRMB = Rtcount
					* Double.parseDouble(dnps.get(0).getDiscountRMB());
		}

		com.marketingexpert.domain.User user = getUserService().queryUserByUId(
				parentUserId);
		try {
			if(minusRMB < Double.parseDouble(discount.getItemPrice())) {
				storeService.updateItemPrice(discount.getItemId(), minusRMB, user.getAccessToken());
			}			
		} catch (MarketingExpertException e) {
			logger.error("������Ʒ��Ϣʧ��", e);
			throw e;
		}

	}

	@Override
	public int queryEnableFuncTotalCounts(String funcCode) {
		try {
			return getMarketingDao().queryEnableFuncTotalCounts(funcCode);
		} catch (DataAccessException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException(e);
		}
	}

	@Override
	public List<UserFuncEnable> queryEnabledFuncPagin(String funcCode, int cursor,
			int pageSize) {
		try {
			return getMarketingDao().queryEnabledFuncPagin(funcCode,cursor, pageSize);
		} catch (DataAccessException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException(e);
		}
	}

	@Override
	public List<Activity> getActivity(String activityId, String sessionKey) {
		StoreService taobaoService = getStoreServiceFactory().getService(
				StoreServiceFactory.TAOBAO);
		try {
			 List<Activity> activitys = taobaoService.getActivity(activityId,sessionKey);
			return activitys;
		} catch (MarketingExpertException e) {
			throw e;
		}
		
	}
}
